/**
 * http工具类
 */
const request = require('request');
const { log } = require('./util')

const DOMAIN = 'https://mvnrepository.com'

//绕过谷歌机器人校验，cookie失效后可使用浏览器进行一次校验，然后拷贝cookie
var cookiejar = request.jar();
let cookie;

cookie = request.cookie('cf_clearance=8aa0873776196a9d25683eda155a2dc9d31a9372-1614241221-0-250');
cookiejar.setCookie(cookie, DOMAIN);

const options = {
    headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
    },
    timeout: 20000,
    jar: cookiejar // Tells rp to include cookies in jar that match uri
}


/**
 * get请求
 * @param {url} url 
 */
function httpGet(url) {
    return new Promise((resolve, reject) => {
        request(Object.assign({ url }, options), (err, res, body) => {
            if (err) {
                console.error(`get url:${url} error ${err}`)
                reject(err)
            }
            log.debug(`get ${url} success.`)
            resolve(body)
        })
    })
}


module.exports = {
    httpGet
}